<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px"
        >
            <el-breadcrumb-item>
                <i class="el-icon-copy-document"></i>
                切片借阅
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-form
                :model="filterForm"
                label-width="70px"
            >
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="病理编号">
                            <el-input
                                v-model="filterForm.pathologyId"
                                placeholder="请输入病理编号"
                                class="input-form"
                                size="mini"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="病人姓名">
                            <el-input
                                v-model="filterForm.patientName"
                                placeholder="请输入病人姓名"
                                class="input-form"
                                size="mini"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="借片姓名">
                            <el-input
                                v-model="filterForm.sliceBorrowName"
                                placeholder="请输入借片姓名"
                                class="input-form"
                                size="mini"
                            >
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="借片日期">
                            <el-date-picker
                                v-model="createdRange"
                                class="time-picker-form"
                                size="mini"
                                type="datetimerange"
                                align="right"
                                unlink-panels
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="借片医生">
                            <el-select
                                placeholder="请选择借片医生"
                                clearable
                                v-model="filterForm.sliceBorrowDoctorId"
                                class="picker-form"
                                size="mini"
                            >
                                <el-option
                                    v-for="item in sliceBorrowDoctorList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col
                        :span="2"
                        :offset="13"
                    >
                        <el-form-item label="">
                            <el-button
                                type="primary"
                                size="mini"
                                @click="searchAll"
                            >搜索</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-form-item label="">
                            <el-button
                                type="primary"
                                size="mini"
                                @click="borrowingRegistration"
                            >借阅登记</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <el-row style="margin-top: 10px">
                <base-table
                    ref="biopsyTable"
                    :data="biopsyTable.data"
                    :header="biopsyTable.header"
                    :operation="biopsyTable.operation"
                    :pageInfo="biopsyTable.pageInfo"
                    @pageJumpTo="biopsyTablePageJumpTo"
                    @sizeChange="biopsyTableSizeChange"
                >
                </base-table>
            </el-row>
            <el-dialog
                title="借阅登记"
                :visible.sync="centerDialogVisible"
                width="50%"
                center
            >
                <el-form
                    :model="filterData"
                    :rules="formRules"
                    label-width="100px"
                >
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="搜索条件">
                                <el-input
                                    v-model="filterData.pathologyIdOrName"
                                    placeholder="请输入病理编号或者姓名在搜索"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <el-form-item>
                                <el-button
                                    type="primary"
                                    size="mini"
                                    @click="searchByPathologyIdOrName"
                                >搜 索</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <el-form-item>
                                <el-button
                                    type="primary"
                                    size="mini"
                                >借片二维码</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="病人姓名">
                                <el-input
                                    v-model="filterData.patientName"
                                    placeholder="请输入病人姓名"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="病理编号">
                                <el-input
                                    v-model="filterData.pathologyId"
                                    placeholder="请输入病理编号"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="病人性别">
                                <el-select
                                    v-model="filterData.patientSex"
                                    placeholder="请选择性别"
                                    size="mini"
                                    class="picker-form"
                                >
                                    <el-option
                                        v-for="(data, index) in SexKindList"
                                        :key="index"
                                        :label="data.name"
                                        :value="data.id"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item
                                label="借片人姓名"
                                prop="sliceBorrowName"
                            >
                                <el-input
                                    v-model="filterData.sliceBorrowName"
                                    placeholder="请输入借片人姓名"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="与患者关系"
                                prop="relationWithPatient"
                            >
                                <el-input
                                    v-model="filterData.relationWithPatient"
                                    placeholder="请输入与患者关系"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item
                                label="联系电话"
                                prop="contactCellphone"
                            >
                                <el-input
                                    v-model="filterData.contactCellphone"
                                    placeholder="请输入联系电话"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="病人年龄">
                                <el-input
                                    v-model="filterData.patientAge"
                                    placeholder="请输入病人年龄"
                                    class="input-form"
                                    size="mini"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <el-row style="margin:30px;">
                    <span>病人切片：</span>
                    <el-checkbox
                        :indeterminate="isIndeterminate"
                        v-model="checkAll"
                        @change="handleCheckAllChange"
                    >全选
                    </el-checkbox>
                </el-row>
                <el-row>
                    <div class="image-container">
                        <el-checkbox-group
                            v-model="checkedPics"
                            @change="handleCheckedPicsChange"
                        >
                            <el-checkbox
                                v-for="pic in pics"
                                :label="pic.targetPath"
                                :key="pic.targetPath"
                            >
                                <img
                                    :src="imageServiceURL+pic.labelUrl"
                                    style="width:150px;height:150px;margin-right:25px;"
                                />
                                <img
                                    :src="imageServiceURL+pic.previewUrl"
                                    style="width:150px;height:150px;"
                                />
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-row>
                <span
                    slot="footer"
                    class="dialog-footer"
                >
                    <el-button
                        type="primary"
                        size="mini"
                        @click="centerDialogVisible = false"
                    >取 消</el-button>
                    <el-button
                        type="primary"
                        size="mini"
                        :loading="loadSliceStatus"
                        @click="downloadSlice"
                    >下载切片</el-button>
                    <el-button
                        type="primary"
                        size="mini"
                        @click="btnSure"
                    >确定</el-button>
                </span>
            </el-dialog>
            <el-dialog
                title="借阅登记搜索列表"
                :visible.sync="searchListDialogVisible"
                width="50%"
                center
            >
                <el-table
                    :data="tableListData"
                    border
                    :cell-style="{'text-align':'center'}"
                    :header-cell-style="{
                'background-color': '#E6E9EF',
                'color':'#777C7C',
                'font-weight':'400',
                'font-size' : '15px',
                'border-right': '1px solid #ffffff',
                'text-align':'center'}"
                    size="mini"
                    style="width: 100%;"
                >
                    <el-table-column
                        prop="pathologyId"
                        label="病理编号"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="patientName"
                        label="病人姓名"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="patientSexName"
                        label="病人性别"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="patientAge"
                        label="病人年龄"
                    >
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button
                                @click="choosePatient(scope.row)"
                                type="text"
                                size="small"
                            >选择</el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import { itemsPerPage } from '@/client/libs/util';
import moment from 'moment/moment';
export default {
    name: 'sliceBorrow',
    components: {
        BaseTable,
    },
    data() {
        return {
            imageServiceURL: process.env.ImageServiceURL,
            pathologyServiceURL: process.env.pathologyServiceURL,
            filterForm: {
                pathologyId: '', //病理号
                patientName: '', //病人姓名
                sliceBorrowDoctorId: '', //借片医生ID
                sliceBorrowEndTime: '', //借片结束日期
                sliceBorrowName: '', //借片人姓名
                sliceBorrowStartTime: '', //借片开始日期
                page: '',
                size: '',
            },
            tableListData: [],
            sliceBorrowDoctorList: [],
            createdRange: [],
            formRules: {
                sliceBorrowName: [
                    {
                        required: true,
                        message: '借片人姓名不能为空',
                        trigger: 'blur',
                    },
                ],
                relationWithPatient: [
                    {
                        required: true,
                        message: '与患者关系不能为空',
                        trigger: 'blur',
                    },
                ],
                contactCellphone: [
                    {
                        required: true,
                        message: '联系电话不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            checkAll: false,
            checkedPics: [],
            isIndeterminate: true,
            pics: [],
            bindPics: [],

            centerDialogVisible: false,
            searchListDialogVisible: false,
            loadSliceStatus: false,
            SexKindList: [],
            dictRequestMap: [
                {
                    code: 'SexKind',
                    arrayKey: 'SexKindList',
                },
            ],
            biopsyTable: {
                data: [],
                header: [
                    {
                        label: '借片人姓名',
                        prop: 'sliceBorrowName',
                    },
                    {
                        label: '与患者关系',
                        prop: 'relationWithPatient',
                    },
                    {
                        label: '联系电话',
                        prop: 'contactCellphone',
                    },
                    {
                        label: '病理编号',
                        prop: 'pathologyId',
                    },
                    {
                        label: '病人姓名',
                        prop: 'patientName',
                    },
                    {
                        label: '病人性别',
                        prop: 'patientSexName',
                    },
                    {
                        label: '病人年龄',
                        prop: 'patientAge',
                    },

                    {
                        label: '借片日期',
                        prop: 'sliceBorrowTime',
                    },
                    {
                        label: '借片医生',
                        prop: 'sliceBorrowDoctorName',
                    },
                ],
                operation: [],
                // 分页信息
                pageInfo: {
                    size: itemsPerPage.get(),
                    page: 1,
                    total: 0,
                },
            },
            filterData: {
                pathologyIdOrName: '', //模糊搜索条件
                pathologyId: '', //病人病理号，从1.1的接口取值
                patientAge: '', //病人年龄，从1.1的接口取值
                patientAgeUnit: '', //病人年龄单位，从1.1的接口取值
                patientName: '', //病人姓名，从1.1的接口取值
                patientSex: '', //病人性别，从1.1的接口取值
                contactCellphone: '', //联系电话
                relationWithPatient: '', //与患者的关系
                sliceBorrowName: '', //借片人姓名
                sliceBorrowRemark: '', //备注
            },
        };
    },
    mounted() {
        this.getBiopsyTableData();
        this.dictionariesRequest();
        this.getSliceBorrowDoctorList();
    },
    methods: {
        getSliceBorrowDoctorList() {
            this.$axios({
                method: 'get',
                url: '/users/searchScanName ',
            }).then(async (res) => {
                if (res && res.data.code === 200) {
                    res.data.data.forEach((item) => {
                        this.sliceBorrowDoctorList.push({
                            label: item.scanName,
                            value: item.scanId,
                        });
                    });
                }
            });
        },
        dictionariesRequest() {
            this.dictRequestMap.forEach((map) => {
                this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/dicts/list',
                    params: {
                        code: map.code,
                        page: 0,
                        size: 99,
                    },
                }).then((res) => {
                    if (res && res.data.code === 200) {
                        this[map.arrayKey] = _.clone(res.data.data);
                    }
                });
            });
        },
        btnSure() {
            if (
                this.filterData.contactCellphone === '' ||
                this.filterData.relationWithPatient === '' ||
                this.filterData.sliceBorrowName === ''
            ) {
                this.$message.warning('必填信息不能为空');
                return;
            } else {
                this.$axios({
                    method: 'PUT',
                    url: '/PROXY-Remote/slice_borrow/save',
                    data: this.filterData,
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.$message.success('借阅成功');
                    }
                });
            }
        },
        downloadSlice() {
            if (
                this.filterData.contactCellphone === '' ||
                this.filterData.relationWithPatient === '' ||
                this.filterData.sliceBorrowName === ''
            ) {
                this.$message.warning('必填信息不能为空');
                return;
            } else if (this.checkedPics.length == 0) {
                this.$message.warning('请选择下载切片');
                return;
            } else {
                this.$axios({
                    method: 'PUT',
                    url: '/PROXY-Remote/slice_borrow/save',
                    data: this.filterData,
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.loadSliceStatus = true;
                        let mIndex = 0;
                        this.checkedPics.forEach((item) => {
                            let _this = this;
                            let fileSvs = item.split('/');
                            let url = `${this.pathologyServiceURL}/download/${fileSvs[3]}`;
                            let first = url.lastIndexOf('.'); //取到文件名开始到最后一个点的长度
                            let nameLength = url.length; //取到文件名长度
                            let fileSuffix = url.substring(
                                first + 1,
                                nameLength
                            ); //截取获得后缀名
                            const x = new XMLHttpRequest();
                            x.open('GET', url, true);
                            x.responseType = 'blob';
                            x.onload = function (e) {
                                mIndex++;
                                // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
                                const mUrl = window.URL.createObjectURL(
                                    x.response
                                );
                                const a = document.createElement('a');
                                a.href = mUrl;
                                a.download =
                                    _this.filterData.patientName +
                                    _this.filterData.pathologyId +
                                    '.' +
                                    fileSuffix;
                                a.click();
                                if (mIndex === _this.checkedPics.length) {
                                    _this.loadSliceStatus = false;
                                }
                            };
                            x.send();
                        });
                    }
                });
            }
        },
        searchAll() {
            this.getBiopsyTableData();
        },
        borrowingRegistration() {
            this.filterData = {
                pathologyIdOrName: '', //模糊搜索条件
                pathologyId: '', //病人病理号，从1.1的接口取值
                patientAge: '', //病人年龄，从1.1的接口取值
                patientAgeUnit: '', //病人年龄单位，从1.1的接口取值
                patientName: '', //病人姓名，从1.1的接口取值
                patientSex: '', //病人性别，从1.1的接口取值
                contactCellphone: '', //联系电话
                relationWithPatient: '', //与患者的关系
                sliceBorrowName: '', //借片人姓名
                sliceBorrowRemark: '', //备注
            };
            this.pics = [];
            this.centerDialogVisible = true;
        },
        // 分页跳转
        biopsyTablePageJumpTo(val) {
            this.biopsyTable.pageInfo.page = val;
            this.getBiopsyTableData();
        },
        // 每页显示数量改变
        biopsyTableSizeChange(val) {
            this.biopsyTable.pageInfo.size = val;
            this.getBiopsyTableData();
        },
        getBiopsyTableData() {
            if (this.createdRange && this.createdRange.length > 0) {
                let createTimeStart = '';
                let createTimeEnd = '';
                [createTimeStart, createTimeEnd] = this.createdRange;
                this.filterForm.sliceBorrowStartTime = moment(createTimeStart)
                    .format('YYYY-MM-DD hh:mm:ss')
                    .replace(' ', ' ');
                this.filterForm.sliceBorrowEndTime = moment(createTimeEnd)
                    .format('YYYY-MM-DD hh:mm:ss')
                    .replace(' ', ' ');
            } else {
                this.filterForm.sliceBorrowStartTime = '';
                this.filterForm.sliceBorrowEndTime = '';
            }
            this.filterForm.page = this.biopsyTable.pageInfo.page - 1;
            this.filterForm.size = this.biopsyTable.pageInfo.size;
            this.$axios({
                method: 'POST',
                url: '/PROXY-Remote/slice_borrow/findAll',
                data: this.filterForm,
            }).then((res) => {
                if (res.data.code === 200) {
                    this.biopsyTable.data = res.data.data;
                    this.biopsyTable.pageInfo = {
                        total: res.data.pageInfo.total,
                        page: res.data.pageInfo.page + 1,
                        size: res.data.pageInfo.size,
                    };
                }
            });
        },
        searchByPathologyIdOrName() {
            if (this.filterData.pathologyIdOrName) {
                this.$axios({
                    method: 'GET',
                    url: `/PROXY-Remote/diagnosis/forSliceBorrow/getBiopsyAndDiagnosis/by/${this.filterData.pathologyIdOrName}`,
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.tableListData = res.data.data;
                        this.searchListDialogVisible = true;
                    }
                });
            } else {
                this.$message.warning('请输入搜索条件');
            }
        },
        choosePatient(row) {
            this.searchListDialogVisible = false;
            this.pics = row.sliceBorrowOfBiopsyInfoList;
            this.pics.forEach((item) => {
                this.bindPics.push(item.targetPath);
            });
            this.filterData.patientAge = row.patientAge;
            this.filterData.patientAgeUnit = row.patientAgeUnit;
            this.filterData.patientName = row.patientName;
            this.filterData.patientSex = row.patientSex;
            this.filterData.pathologyId = row.pathologyId;
        },
        // 点击全选
        handleCheckAllChange(val) {
            this.checkedPics = val ? this.bindPics : [];
            this.isIndeterminate = false;
        },
        // 点击选择单个图片
        handleCheckedPicsChange(value) {
            const checkedCount = value.length;
            this.checkAll = checkedCount === this.pics.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.pics.length;
        },
    },
};
</script>

<style scoped>
.image-container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

/deep/ .image-container .el-checkbox .el-checkbox__input {
    vertical-align: top;
}
</style>